using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

namespace WindowsGame
{
  public class AnimatedSprite
  {
    #region Private fields

    private Texture2D mTexture;

    private float mTotalElapsed;
    private float mAnimationSpeed;

    private int mRows;
    private int mColumns;
    private int mWidth;
    private int mHeight;
    private int mCurrentRow;
    private int mCurrentColumn;

    #endregion

    #region Public properties

    public Texture2D Texture
    {
      get
      {
        return this.mTexture;
      }
      set
      {
        if (this.mTexture != value)
        {
          this.mTexture = value;
        }
      }
    }

    #endregion

    #region Public methods

    public void LoadGraphic(Texture2D texture, int rows, int columns, int width, int height, int animationSpeed)
    {
      this.mTexture        = texture;
      this.mRows           = rows;
      this.mColumns        = columns;
      this.mWidth          = width;
      this.mHeight         = height;
      this.mAnimationSpeed = 1F / animationSpeed;
      this.mTotalElapsed   = 0;
      this.mCurrentRow     = 0;
      this.mCurrentColumn  = 0;
    }

    public void Update(float elapsed)
    {
      this.mTotalElapsed += elapsed;

      if (this.mTotalElapsed > this.mAnimationSpeed)
      {
        this.mTotalElapsed -= this.mAnimationSpeed;
        this.mCurrentColumn++;

        if (this.mCurrentColumn >= this.mColumns)
        {
          this.mCurrentRow++;
          this.mCurrentColumn = 0;

          if (this.mCurrentRow >= this.mRows)
          {
            this.mCurrentRow = 0;
          }
        }
      }
    }

    public void Draw(SpriteBatch sprite, Vector2 position, Color color)
    {
      sprite.Draw(this.mTexture, new Rectangle((int)position.X, (int)position.Y, this.mWidth, this.mHeight),
          new Rectangle(this.mCurrentColumn * this.mWidth, this.mCurrentRow * this.mHeight, this.mWidth, this.mHeight), color);
    }

    #endregion
  }
}
